<template>
  <el-dialog
    title="新增区域"
    :visible.sync="visible"
    width="850px"
    append-to-body
  >
    <avue-form
      ref="addForm"
      v-model="form"
      :option="areaFormOption"
    >
      <template #succeedAdoptPic>
        <div>
          <div
            v-if="succeedAdoptPic"
            class="lottie-wrap"
            @mouseenter="showDel"
            @mouseleave="handleMouseLeave"
          >
            <div class="adoptPic"></div>
            <div
              v-if="showDelFlag"
              class="mask"
            >
              <i
                class="el-icon-delete del-icon"
                @click="resetLottie"
              ></i>
            </div>
          </div>

          <el-upload
            v-else
            ref="upload"
            :on-success="handleSuccess"
            accept=".json"
            :on-format-error="handleFormatError"
            :on-remove="handleRemove"
            :max-size="1024"
            :on-exceeded-size="handleMaxSize"
            type="drag"
            :data="qnToken"
            :limit="1"
            :show-file-list="false"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :action="uploadUrl"
          >
            <i
              slot="default"
              class="el-icon-plus"
            ></i>
            <!-- <div
              slot="tip"
              class="el-upload__tip"
            >
              用户进入app时，根据猫咪所属区域展示云认养成功飘屏动图,请上传json格式的动画
            </div> -->
          </el-upload>
          <div style="font-size: 12px; color: #606266; margin-top: 7px">
            用户进入app时，根据猫咪所属区域展示云认养成功飘屏动图,请上传json格式的动画
          </div>
        </div>
      </template>
    </avue-form>
    <template #footer>
      <el-button
        type="primary"
        :loading="loading"
        @click="save"
      >
        确定
      </el-button>
      <el-button @click="visible = false">取消</el-button>
    </template>
  </el-dialog>
</template>
<script>
import { areaFormOption } from '@/const/crud/pet/adoptionArea.js';
import {
  addAdoptArea,
  getAdoptAreaDetail,
  updateAdoptArea,
} from '@/api/core/adopt';
import Lottie from 'lottie-web';
import store from '@/store';
import { getQNToken } from '@/api/upload.js';
export default {
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      areaFormOption,
      form: {},
      loading: false,
      qnToken: {},
      uploadUrl: process.env.VUE_APP_QINIU_URL,
      succeedAdoptPic: '',
      showDelFlag: false,
    };
  },
  computed: {
    visible: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      },
    },
    headers: function () {
      const tenantId = store.getters.userInfo.tenantId;
      return {
        Authorization: 'Bearer ' + store.getters.access_token,
        'TENANT-ID': tenantId ? tenantId : '1',
      };
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.getQNToken();
        if (this.id) {
          this.getAdoptAreaDetail();
        }
      } else {
        this.succeedAdoptPic = '';
        this.$refs.addForm && this.$refs.addForm.resetFields();
      }
    },
  },
  methods: {
    getAdoptAreaDetail() {
      getAdoptAreaDetail(this.id).then((res) => {
        this.form = res.data.data;
        this.succeedAdoptPic = this.form.succeedAdoptPic;
        this.form.mpSucceedAdoptPic = JSON.parse(
          this.form.mpSucceedAdoptPic || '[]'
        );
        setTimeout(() => {
          this.loadLottie();
        }, 100);
      });
    },
    save() {
      console.log(this.form);
      this.$refs.addForm.validate(async (valid, done) => {
        if (valid) {
          try {
            this.loading = true;
            this.form.baseName = this.form.$baseId;
            const params = {
              ...this.form,
              mpSucceedAdoptPic: JSON.stringify(this.form.mpSucceedAdoptPic),
            };
            if (this.id) {
              await updateAdoptArea(params);
              this.$message.success('修改成功');
            } else {
              await addAdoptArea(params);
              this.$message.success('添加成功');
            }
            this.$emit('onSuccess');
            this.loading = false;
            this.visible = false;
            done();
          } catch (error) {
            this.loading = false;
            done();
            throw new Error(error);
          }
        }
      });
    },
    //获取七牛token
    getQNToken() {
      getQNToken().then((res) => {
        if (res.data.code === 0) {
          this.qnToken = { token: res.data.data };
        }
      });
    },
    ///预览动画
    loadLottie() {
      const el = document.querySelector('.adoptPic');
      if (el) {
        console.log(this.succeedAdoptPic);
        Lottie.loadAnimation({
          container: el, // the dom element that will contain the animation
          renderer: 'svg',
          loop: true,
          autoplay: true,
          path: this.succeedAdoptPic, // the path to the animation json
        });
      }
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: '图片超过限制大小！',
        desc: '图片超过规定限制大小，请重新上传',
      });
    },
    beforeUpload(file) {
      console.log(file);
      const isJSON = file.type === 'application/json';
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJSON) {
        this.$message.error('上传的文件只能是json格式');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }
    },

    handleSuccess(res) {
      this.succeedAdoptPic = `${this.$configObj.url}/${res.key}`;
      this.form.succeedAdoptPic = this.succeedAdoptPic;
      setTimeout(() => {
        this.loadLottie();
      }, 100);
    },
    handleFormatError() {},
    handleRemove() {},
    showDel() {
      this.showDelFlag = true;
    },
    handleMouseLeave() {
      this.showDelFlag = false;
    },
    resetLottie() {
      this.succeedAdoptPic = '';
      this.form.succeedAdoptPic = '';
    },
  },
};
</script>

<style lang="scss" scoped>
.lottie-wrap {
  width: 148px;
  height: 148px;
  position: relative;
  .mask {
    background-color: rgba(0, 0, 0, 0.5);
    top: 0;
    left: 0;
    width: 148px;
    height: 148px;
    position: absolute;
    border-radius: 8px;
    cursor: pointer;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    .del-icon {
      font-size: 30px;
      color: #ffffff;
      top: 0;
      bottom: 0;
    }
  }
  .adoptPic {
    width: 148px;
    height: 148px;
    position: absolute;
    top: 0;
  }
}
</style>
